package com.tongtong.stscommon.proxy;

import com.tongtong.stscommon.enumration.Message;
import com.tongtong.stscommon.enumration.Status;
import com.tongtong.stscommon.exception.STSAuthenticationException;
import org.aspectj.lang.ProceedingJoinPoint;
import org.aspectj.lang.annotation.Around;
import org.aspectj.lang.annotation.Aspect;
import org.aspectj.lang.annotation.Pointcut;
import org.springframework.security.core.Authentication;
import org.springframework.security.core.context.SecurityContextHolder;
import org.springframework.stereotype.Component;

@Component
@Aspect
public class IdAOP {

	@Pointcut("@annotation(com.tongtong.stscommon.proxy.annotation.AutoGetId)")
	public void IdAspect() {
	}

	@Around(value = "IdAspect()")
	public Object around(ProceedingJoinPoint proceedingJoinPoint) throws Throwable {
		// 获取目标方法的参数
		Object[] args = proceedingJoinPoint.getArgs();

		Long id;
		try
		{
			Authentication authentication = SecurityContextHolder.getContext().getAuthentication();
			id = Long.parseLong((String) authentication.getCredentials());
		} catch (Exception e) {
			throw new STSAuthenticationException(Status.Unauthorized, Message.Unauthorized);
		}

		args[0] = id; // 设置id=1

		// 执行目标方法，并将新的参数传递进去
		return proceedingJoinPoint.proceed(args);
	}

}
